package com.thank.concurrency.samples.concurrentContainer;

import com.thank.concurrency.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.*;

/**
 * 演示ConcurrentSkipListMap线程安全
 */
@ThreadSafe
@Slf4j
public class ConcurrentSkipListMapExample {

    public static int clientTotal = 5000;
    public static int threadTotal = 200;

    private static Map<Integer, Integer> map = new ConcurrentSkipListMap<>();

    public static void main(String[] args) throws InterruptedException {

        ExecutorService executorService = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            final int x = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add(x);
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception: ", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();

        log.info("map.size()= {}", map.size());
    }

    private static void add(int x) {
        map.put(x, x);
    }
}
